"""
MCP消息模型

用于存储MCP消息记录，支持消息追踪和调试
"""

from sqlalchemy import Column, String, Integer, DateTime, JSON, Text, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database import Base
import enum


class MessageType(str, enum.Enum):
    """消息类型枚举"""
    CONNECT = "CONNECT"
    CONNECT_ACK = "CONNECT_ACK"
    REQUEST = "REQUEST"
    RESPONSE = "RESPONSE"
    ERROR = "ERROR"
    PING = "PING"
    PONG = "PONG"
    DISCONNECT = "DISCONNECT"


class MessageDirection(str, enum.Enum):
    """消息方向枚举"""
    SEND = "send"
    RECEIVE = "receive"


class MessageStatus(str, enum.Enum):
    """消息状态枚举"""
    PENDING = "pending"
    SENT = "sent"
    RECEIVED = "received"
    FAILED = "failed"


class MCPMessage(Base):
    """
    MCP消息表
    
    记录所有MCP消息，用于调试和性能分析
    """
    __tablename__ = "mcp_messages"
    
    # 主键
    id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment="主键")
    
    # 会话关联
    session_id = Column(String(128), ForeignKey("mcp_sessions.session_id", ondelete="CASCADE"), nullable=False, index=True, comment="MCP会话ID")
    message_id = Column(String(128), unique=True, nullable=False, index=True, comment="消息ID（UUID）")
    
    # 消息内容
    message_type = Column(
        Enum(MessageType),
        nullable=False,
        index=True,
        comment="消息类型"
    )
    direction = Column(
        Enum(MessageDirection),
        nullable=False,
        comment="消息方向"
    )
    payload = Column(JSON, nullable=False, comment="消息负载")
    
    # 状态信息
    status = Column(
        Enum(MessageStatus),
        default=MessageStatus.PENDING,
        nullable=False,
        index=True,
        comment="消息状态"
    )
    error_message = Column(Text, comment="错误信息")
    
    # 性能指标
    send_at = Column(DateTime(timezone=True), comment="发送时间")
    receive_at = Column(DateTime(timezone=True), comment="接收时间")
    duration_ms = Column(Integer, comment="处理时长（毫秒）")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True, comment="创建时间")
    
    # 关系
    session = relationship("MCPSession", back_populates="messages")
    
    def __repr__(self):
        return f"<MCPMessage(id={self.id}, type={self.message_type}, direction={self.direction}, status={self.status})>"

